﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Fadd.Net
{
	public class FileReceiver
	{
		private SimpleServer _server;
		private byte[] _inbuffer = new byte[65535];
		private Socket _socket;

		public void Start(IPAddress address, int port)
		{
			
		}

		/// <summary>
		/// Read file 
		/// </summary>
		/// <param name="path">Where to save the file</param>
		/// <remarks>
		/// Filename is transfered over the socket. 
		/// </remarks>
		public void ReadFile(string path)
		{
			ReadBytes(8);
			int length = BitConverter.ToInt32(_inbuffer, 0);
			ReadBytes(length);

			FileHeader header;

			using (var stream = new MemoryStream())
			{
				stream.Write(_inbuffer, 0, length);
				stream.Flush();
				stream.Position = 0;

				var formatter = new BinaryFormatter();
				header = (FileHeader)formatter.Deserialize(stream);
			}

			WriteToFile(header);
			FileReceived(this, new FileEventArgs(header.FileName));
		}


		/// <summary>
		/// A file have been received.
		/// </summary>
		public event EventHandler<FileEventArgs> FileReceived = delegate { };



		private void WriteToFile(FileHeader header)
		{
			int bytesLeft = header.Size;

			using (var stream = new FileStream(header.FileName, FileMode.Create, FileAccess.Write, FileShare.Read))
			{
				int bytesRead = _socket.Receive(_inbuffer);
				while (bytesLeft > 0)
				{
					stream.Write(_inbuffer, 0, bytesRead);
					bytesLeft -= bytesRead;
					bytesRead = _socket.Receive(_inbuffer, 0, Math.Min(_inbuffer.Length, bytesLeft), SocketFlags.None);
				}
			}
		}

		private void ReadBytes(int count)
		{
			int bytesRead = _socket.Receive(_inbuffer, 0, 8, SocketFlags.None);
			while (bytesRead < count)
				bytesRead += _socket.Receive(_inbuffer, bytesRead, count - bytesRead, SocketFlags.None);
		}

	}
}
